package org.lim.lcpicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lim.lcpicturebackend.annotation.AuthCheck;
import org.lim.lcpicturebackend.common.BaseResponse;
import org.lim.lcpicturebackend.common.DeleteRequest;
import org.lim.lcpicturebackend.common.ResultUtils;
import org.lim.lcpicturebackend.constant.PasswordConstant;
import org.lim.lcpicturebackend.constant.UserConstant;
import org.lim.lcpicturebackend.exception.BusinessException;
import org.lim.lcpicturebackend.exception.ErrorCode;
import org.lim.lcpicturebackend.exception.ThrowUtils;
import org.lim.lcpicturebackend.model.dto.user.*;
import org.lim.lcpicturebackend.model.entity.User;
import org.lim.lcpicturebackend.model.enums.UserRoleEnum;
import org.lim.lcpicturebackend.model.vo.user.LoginUserVO;
import org.lim.lcpicturebackend.model.vo.user.UserVO;

import org.lim.lcpicturebackend.properties.JwtProperties;
import org.lim.lcpicturebackend.service.UserService;
import org.lim.lcpicturebackend.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;
//    @Resource
//    private JwtProperties jwtProperties;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {

        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }
    /**
     * 用户登录
     * session方法
     *
     *
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //放到service做判断
//        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        LoginUserVO result = userService.userLogin(userLoginRequest, request);
        return ResultUtils.success(result);
    }

//    /**
//     * 用户登录
//     * jwt方法
//     */
//    @PostMapping("/login")
//    public BaseResponse userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
//        //放到service做判断
////        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
//        LoginUserVO result = userService.userLogin(userLoginRequest, request);
//        if (result != null) {
//            HashMap<String, Object> claims = new HashMap<>();
//            claims.put("id", result.getId());
//            result.setToken(JwtUtils.createJwt(jwtProperties.getSecretKey(), jwtProperties.getTtlMillis(), claims));
//
//            return ResultUtils.success(result);
//        }
//        return ResultUtils.error(ErrorCode.PARAMS_ERROR);
//    }

    /**
     * @Description: 获取当前登录用户信息
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVo(loginUser));
    }
//    @GetMapping("/get/login")
//    public BaseResponse<LoginUserVO> getLoginUser() {
//        User loginUser = userService.getLoginUser();
//        return ResultUtils.success(userService.getLoginUserVo(loginUser));
//    }

        @PostMapping("logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        userService.userLogout(request);
        return ResultUtils.success(true);
    }
//    @PostMapping("logout")
//    public BaseResponse<Boolean> userLogout() {
//        userService.userLogout();
//        return ResultUtils.success(true);
//    }

    /**
     * 添加用户(限管理员)
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 设置默认密码
        String encryptPassword = userService.getEncryptPassword(PasswordConstant.DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);

        //插入数据库
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }
    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }
    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }
    /**
     * 更新用户，只能更新自己
     */
    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
/*    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }*/
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        // 校验请求参数
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);

        // 获取分页参数，若未指定则使用默认值
        long current = Optional.of(userQueryRequest.getCurrent()).orElse(1);
        long pageSize = Optional.of(userQueryRequest.getPageSize()).orElse(10);

        // 创建查询条件并一步获取分页用户数据
        Page<User> userPage = userService.pageUsers(current, pageSize, userQueryRequest);

        // 使用高效转换方法将用户实体转换为VO
        return ResultUtils.success(userService.convertToUserVOPage(userPage));
    }

}
